from flask import Blueprint, request
from entity.Response import success,error
from entity.Video import Video
from entity.User import User
from db import db
from controller.LoginController import getUsername
from sqlalchemy import desc
import random

videoController = Blueprint('videoController',__name__)

"""
上传视频
input:
video form
output:
none
"""
@videoController.route('/uploadVideo',methods=['POST'])
def uploadVideo():
    title = request.get_json().get('title')
    cover = request.get_json().get('cover')
    videoSrc = request.get_json().get('videoSrc')
    introduciton = request.get_json().get('introduction')
    username = getUsername()

    video = Video(title,cover,videoSrc,username,introduciton)
    db.session.add(video)
    db.session.commit()

    return success(message='视频上传成功')

"""
获取全部视频
input
type 获取的方式 0-按最新视频获取 1-按最热视频获取
output
video list
"""
@videoController.route('/getVideoList',methods=['GET'])
def getVideoList():
    searchType = request.args.get('searchType')
    searchType = int(searchType)
    if searchType == 0:
        videoList = Video.query.order_by(desc(Video.create_time)).all()
    else:
        videoList = Video.query.order_by(desc(Video.view)).all()
    dataList = []
    for video in videoList:
        user = User.query.filter_by(username=video.username).first()
        dataDict = video.to_dict()
        dataDict['avatar'] = user.avatar
        dataDict['hospital'] = user.hospital
        dataDict['phone'] = user.phone
        dataList.append(dataDict)

    return success(message='获取视频列表成功',data=dataList)

"""
点击视频 增加视频播放量
input:
video id
output:
None
"""
@videoController.route('/clickVideo',methods=['PUT'])
def clickVideo():
    videoId = request.args.get('videoId')

    video = Video.query.filter_by(id=videoId).first()
    if video == None:
        return error(message='视频不存在')
    
    Video.query.filter_by(id=videoId).update({'view': video.view + 1})
    db.session.commit()
    
    return success(message='点击视频成功',data=None)

"""
获取推荐视频
input:
videoId
output:
video list
"""
@videoController.route('/getRecommendVideo', methods=['GET'])
def getRecommendVideo():
    videoId = request.args.get('videoId')

    # 先查询一共有多少条
    videoList = Video.query.all()
    total_count = len(videoList)

    # 随机获取5个index，要求对应的videoList[index].id != videoId
    cnt = 0
    selected_indices = []
    while cnt < 5:
        random_index = random.randint(0, total_count - 1)
        if videoList[random_index].id != videoId and random_index not in selected_indices:
            selected_indices.append(random_index)
            cnt += 1

    # 根据选中的索引获取视频对象
    recommended_videos = [videoList[index] for index in selected_indices]
    dataList = []
    for video in recommended_videos:
        dataList.append(video.to_dict())

    return success(message='获取推荐视频成功',data=dataList)